import React, { useEffect, useRef, useState } from "react"
import { wxLoginCheck,wxLogin} from './api'
import styles from './login.module.scss'

let wechatNumber = ''
let checkWechatLoginNum = 0
let checkWechatLoginStatusTimeout = 0
let checkLoginStatusTimeout = 0
let checkLoginNum = 0
export function LoginWx(props: { getUserInfo: (arg0: boolean) => void; loginType: string; loginMode: string; }) {
    const { loginType, loginMode, getUserInfo } = props
    const [isInvalid, setIsInvalid] = useState(false)

    const [isShowWxRefer, setIsShowWxRefer] = useState(false)

    const wxRefer = useRef<HTMLImageElement>(null)
    const CodeProblemDom = useRef<HTMLSpanElement>(null)
    /**
     * 获取微信登录二维码
     */
    const getWechatQrcode = () => {
        setIsInvalid(false)
        setIsShowWxRefer(false)
        let wxReferDom = wxRefer.current as HTMLImageElement;
        let getQrcodeUrl = wxReferDom.getAttribute('data-href') as string;
        fetch(getQrcodeUrl, { credentials: 'include' }).then(data => {
            data.json().then(resultData => {
                if (resultData.stat === 1) {
                    wechatNumber = resultData.msg.number;
                    wxReferDom.setAttribute('src', resultData.msg.Qrcode);
                    setIsShowWxRefer(true)
                    setIsInvalid(false)
                    invalidTimeout();
                    checkWechatLoginStatus(1);
                }
            });
        });
    }

    /**
     * 微信二维码过期（计时）
     */
    const invalidTimeout = () => {
        setTimeout(function () {
            setIsInvalid(true)
        }, 60000);
    }

    /**
     * 微信登录检测
     * @param isInit
     */
    const checkWechatLoginStatus = (isInit = 0) => {
        if (isInit) {
            checkWechatLoginNum = 0;
        }
        checkWechatLoginNum++;
        if (checkWechatLoginNum < 31) {
            checkWechatLoginStatusTimeout = window.setTimeout(function () {
                checkWechatLoginStatus();
            }, 2000);
            wxLoginCheck(wechatNumber).then(resultData => {
                if (resultData.msg == 'invalid' || resultData.msg == 'expired') {
                    if (checkWechatLoginStatusTimeout) {
                        clearTimeout(checkWechatLoginStatusTimeout);
                    }
                    setIsInvalid(true)
                }
                if (resultData.stat == 1) {
                    clearTimeout(checkWechatLoginStatusTimeout);
                    wxLogin(wechatNumber).then(resultData => {
                        localStorage.setItem("token", resultData.token);
                        props.getUserInfo(true)
                    })
                }
            }).catch(err => { 
                console.log('err---------',err)
            })
        }
    }

    /**
     * 登录信息检测
     * @param isInit
     * @param isLoop
     */
    const checkLoginStatus = (isInit = 0, isLoop = 0) => {
        if (isInit) {
            checkLoginNum = 0;
        }
        checkLoginNum++;
        if (checkLoginNum < 31) {
            if (isLoop) {
                checkLoginStatusTimeout = window.setTimeout(function () {
                    checkLoginStatusTimeout && clearTimeout(checkLoginStatusTimeout);
                    checkLoginStatus(0, 1);
                }, 1000);
            }
            props.getUserInfo(true);
            checkWechatLoginStatusTimeout && clearTimeout(checkWechatLoginStatusTimeout);
        }
    }

    const resMaskClickEvent = (e: { stopPropagation: () => void; nativeEvent: { stopPropagation: () => void } }) => {
        getWechatQrcode();
        e.stopPropagation();
        e.nativeEvent.stopPropagation();
    }
    /**
     * 微信弹窗扫码（点击遇到问题）
     */
    const sweepCodeProblem = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
        let wxReferDom = CodeProblemDom.current as HTMLSpanElement;
        let wxUrl = wxReferDom.getAttribute('data-href') as string;
        window.open(wxUrl, "", "width=750, height=500, top=50, left=50");
        checkLoginStatus(1, 1);
        e.stopPropagation();
        e.nativeEvent.stopPropagation();
    }

    useEffect(() => { 
        getWechatQrcode()
    },[])

    let isClientSide = false;
    return (
        <div className={isInvalid ? `${styles.resQrcodeBox} ${styles.mask}` : styles.resQrcodeBox}>
            <div className={styles.resMask} onClick={resMaskClickEvent}>二维码失效<br />请点击刷新</div>
            <div className={styles.qrcodeImgBox}>
                {loginType == 'wechat' && loginMode == 'wx' &&
                    <div className={styles.loginmode}
                        style={{
                            right: -70,
                        }}>
                        <div className={styles.loginArrow}></div>
                        <div className={styles.loginText}>上次登录</div>
                    </div>
                }
                <img className={styles.wxSys} src="//js.tuguaishou.com/index_img/pay/wx-sys.gif" />
                <img id="wx_refer" ref={ wxRefer} className={isShowWxRefer ? `${styles.resQrcode} ${styles.active}` : styles.resQrcode}
                    data-href={`/site/wechat-login?authclient=official${isClientSide ? '&isClientSide=' + isClientSide : ''}&login_page=${isClientSide ? 'win_ue' : 'ue'}`} />
            </div>
            <p className={styles.wxRefers}>扫码登录遇到问题？
                
                <span onMouseDown={sweepCodeProblem}
                    ref={CodeProblemDom}
                    data-href={`/site/auth?authclient=wechat&isAjax=1${isClientSide ? '&isClientSide=' + isClientSide : ''}&login_page=${isClientSide ? 'win_ue' : 'ue'}`}>
                    点击这里</span>
            </p>
        </div>
    )
}